'use strict';

const BaseService = require('../base');
const wxConfig = require("../../../config/wx");
const WXBizDataCrypt = require('../../../config/WXBizDataCrypt');
class RouterService extends BaseService {
  static get modelName() {
    return 'Business.User';
  }

  getPageInclude() {
    return [
      {
        model: this.ctx.model.Business.User,
        as: 'parent',
      }
    ]
  }
  getListInclude() {
    return [
      {
        model: this.ctx.model.Business.User,
        as: 'parent',
      }
    ]
  }
  getDetailInclude() {
    return [
      {
        model: this.ctx.model.Business.User,
        as: 'parent',
      }
    ]
  }

  async getAccessToken() {
    const tokenRes = await this.ctx.curl(`https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=${wxConfig.appid}&secret=${wxConfig.secret}`, { method: 'GET', dataType: 'json' });
    const token = tokenRes.data.access_token
    if (tokenRes.data.errcode) {
      throw new Error(tokenRes.data.errmsg);
    }
    return token
  }
  // 微信授权一键登录
  async wxLogin(data) {
    const { code } = data;
    try {
      const { openid } = await this.exchangeCodeForSessionKey(code)
      return await this.loginForm(openid)
    } catch (error) {
      console.log(error)
      throw new Error(error);
    }
  }
  // 微信手机号授权一键登录
  async wxLoginForPhone(data) {
    const { code, iv, encryptedData } = data;
    try {
      const { openid, session_key } = await this.exchangeCodeForSessionKey(code)
      const phone = await this.decryptPhoneNumber(session_key, encryptedData, iv)
      return await this.loginForm(openid, phone || '')
    } catch (error) {
      console.log(error)
      throw new Error(error);
    }
  }
  async loginForm(openid, phone) {
    const { User } = this.ctx.model.Business;
    if (!openid) {
      throw new Error('登录失败, openid不能为空');
    }
    // 根据手机号查询用户是否存在
    let user = await User.findOne({
      where: {
        openid
      },
    });
    if (phone) {  
      // 查找手机号是否存在
      let user = await User.findOne({
        where: {
          phone
        },
      });
      if (user) {
        throw new Error('手机号已存在');
      }
    }
    if (!user) {
      // 去注册
      let createUser = await User.create({
        password: '123456',
        openid,
        phone: phone || '',
      })
      const detail =  await this.findById(createUser.id);
      return {
        ...detail.dataValues,
        is_register: 1
      }
    } else {
      return {
        ...user.dataValues,
      }
    }
  }
  // 微信登录授权获取session_key和openid
  async exchangeCodeForSessionKey(code) {
    const url = `https://api.weixin.qq.com/sns/jscode2session?appid=${wxConfig.appid}&secret=${wxConfig.secret}&js_code=${code}&grant_type=authorization_code`;
    const response = await this.ctx.curl(url, { dataType: 'json' });
    const data = response.data;
    console.log(response)
    if (!data.session_key || !data.openid) {
      throw new Error('Failed to exchange code for session_key and openid');
    }
    return {
      session_key: data.session_key,
      openid: data.openid,
    };
  }
  // 微信手机号通过接口授权解密手机号 
  // https://api.weixin.qq.com/wxa/business/getuserphonenumber?access_token=ACCESS_TOKEN
  async getPhoneNumber(query) {
    const { code } = query;
    const token = await this.getAccessToken();
    const url = `https://api.weixin.qq.com/wxa/business/getuserphonenumber?access_token=${token}`;
    const response = await this.ctx.curl(url, {
       method: 'POST',
       dataType: 'json',
       data: { code },
       headers: {
          Accept: 'application/json',
          'Content-Type': 'application/json',
        },
     });
    const data = response.data;
    this.ctx.logger.error(response);
    if (data.errcode === 0) {
      return data.phone_info.purePhoneNumber
    } else {
      throw new Error(data.errmsg);
    }
  }

  decryptPhoneNumber(session_key, encryptedData, iv) {
    const pc = new WXBizDataCrypt(wxConfig.appid, session_key);
    const data = {};
    const errCode = pc.decryptData(encryptedData, iv, data);
    return errCode.phoneNumber
  }

  async getUserQrCode(data) {
    // 邀请码查重
    const hasInvite = await this.model.findOne({ where: { id: data.user_id } })
    if (!hasInvite) {
      throw new Error('用户不存在');
    }
    if (hasInvite.invite_qr_code) {
      return hasInvite.invite_qr_code
    }
    let base64 = await this.ctx.service.common.qrcode.getQrcode('pages/index/index?parent_user_id=' + data.user_id)
    await this.model.update({
      invite_qr_code: base64
    }, {
      where: {
        id: data.user_id
      }
    })
    return base64
  }


  async beforeUpdate(id, payload) {
    let data = {
      ...payload
    }
    // 用户存在
    const user = await this.model.findOne({ where: { id } })
    // 自己是经纪人，上级只能是自己
    if (user.user_type === 3) {
      data.parent_user_id = user.id
      return data
    }
    if (user.parent_user_id) {
      return data
    }
    // 父级用户存在
    if (data.parent_user_id) {
      const parentUser = await this.model.findOne({ where: { id: data.parent_user_id, status: 1 } })
      if (!parentUser) {
        delete data.parent_user_id
        return data
      }
      // 父级不属于经纪人 
      if (parentUser.user_type !== 3) {
        delete data.parent_user_id
        return data
      }
      // 父级用户是自己，且自己不属于经纪人
      if (data.parent_user_id == id && parentUser.user_type !== 3) {
        delete data.parent_user_id
        return data
      }
    }
    return data
  }
}


module.exports = RouterService;
